<?php
declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Session;

/**
 * @project: 兔兔考试系统
 * @author: Mandy
 * @date: 2023/7/20
 * @link: https://www.tutudati.com/
 * @site: 微信搜索-兔兔考试系统
 */
class LoginAuthMiddleware
{
    public function handle($request, Closure $next)
    {
        $authorization = $request->header("Authorization", "");
        if (empty($authorization)) {
            return response(["code" => 101, "msg" => "请先登录", "data" => []], 401);
        }
        $authorization = trim(str_replace("Bearer", "", $authorization));
        if (empty($authorization)) {
            return response(["code" => 101, "msg" => "请先登录", "data" => []], 401);
        }
        $userInfo = Cache::get("login:" . $authorization);
        if (empty($userInfo)) {
            return response(["code" => 101, "msg" => "请先登录", "data" => []], 401);
        }
        $userInfo["login_token"] = $authorization;
        Session::put("userinfo", $userInfo);
        return $next($request);
    }
}
